<template>
	<view class="house-content">
		<view class="tips-box">
			注：请填写真实有效信息
		</view>
		<view class="form-box">
			<u-form :model="form" ref="uForm" label-width="auto">
				<view class="form-item">
					<view class="form-title">
						基本信息
					</view>
					<u-form-item label="房源标题" right-icon='arrow-right'><u-input v-model="form.title"
							placeholder='请填写房源标题' input-align="right" /></u-form-item>
					<!-- <u-form-item label="显示地址" right-icon='arrow-right'>
						<view class="flex-end">
							<u-radio-group v-model="form.isshowAddr" @change="radioGroupChange">
								<u-radio @change="radioChange" v-for="(item, index) in isShowAddlist" :key="index"
									:name="item.name" :disabled="item.disabled">
									{{item.name}}
								</u-radio>
							</u-radio-group>
						</view>
					</u-form-item> -->
					<u-form-item label="房源区域" right-icon='arrow-right'><u-input v-model="form.area"
							placeholder='点击选择房源区域' input-align="right" @click='showArea' type="select"
							readonly /></u-form-item>
					<!-- <u-form-item label="房源地址" right-icon='arrow-right'><u-input v-model="form.address"
							input-align="right" placeholder='点击选择房源地址' type="select" readonly
							@click='selectAddress' /></u-form-item> -->
					<u-form-item label="户型" right-icon='arrow-right'><u-input v-model="form.tags" input-align="right"
							placeholder='点击选择房源户型' @click='showTags' type="select" readonly /></u-form-item>
					<u-form-item label="房源密码" right-icon='arrow-right'><u-input v-model="form.housePassword"
							placeholder='请填写房源密码(非必填)' input-align="right" /></u-form-item>

				</view>
				<view class="form-item">
					<view class="form-title">
						收费信息
					</view>
					<view style="width: 100%; height: 20rpx;"></view>
					<u-subsection :list="priceType" :current="priceTypeCurrent" active-color="#fff"
						button-color='rgb(41, 121, 255)' @change='subChange'></u-subsection>
					<view style="width: 100%; height: 20rpx;"></view>
					<view class="tips">
						注：平台服务费为用户支付总额{{platformMoney}}%。<br><text v-if="priceTypeCurrent == 1">中介费为一个月租金。</text>
					</view>
					<u-form-item :label="item.title" label-position="top" v-for="item in skuList" :key="item.title">
						<view class="price-item">
							<view class="input-item">
								<input v-model="item.price" placeholder='请输入' type="number" />/月
							</view>
							<view class="input-item">
								佣金<input v-model="item.commission" placeholder='请输入' type="number" />元
							</view>
							<view class="input-item">
								显示<text style="width: 20rpx; height: 100%;"></text> <u-switch v-model="item.isShow"
									size='28'></u-switch>
							</view>
						</view>
					</u-form-item>
				</view>
				<view class="form-item">
					<view class="form-title">
						图片信息
					</view>
					<view style="width: 100%; height: 20rpx;"></view>
					<view class="tips">
						有图有真相（最多9张图片、1个视频）
					</view>
					<view style="width: 100%; height: 20rpx;"></view>
					<view class="burst-info">
						<view class="">
							<view style="display: flex;">
								<view class="upload-box" @click="chooseImages">
									<image src="../../static/image.png" mode="widthFix"></image>
									<view>上传图片</view>
								</view>
								<view class="upload-box" @click="chooseVideo">
									<image src="../../static/video.png" mode="widthFix"></image>
									<view>上传视频</view>
								</view>
							</view>
							<view style="width: 100%; height: 20rpx;"></view>
							<!-- 图片 -->
							<view style="display: flex;flex-wrap: wrap;">
								<view class="uploader_video" v-for="(image,index) in imageList" :key="index">
									<view class="icon iconfont icon-cuo" @click="delect(index)">X</view>
									<image class="video" :src="image.url" @click="previewImage(index)">
									</image>
								</view>
							</view>

							<!-- 视频 -->
							<view style="margin-top: 20rpx;" class="" v-if="src">
								<view class="uploader_video">
									<view class="icon iconfont icon-cuo" @click="delectVideo">X</view>
									<video :src="src" class="video">视频上传</video>
								</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 	<view class="form-item">
					<view class="form-title">
						房主信息
					</view>
					<u-form-item label="联系微信" right-icon='arrow-right'><u-input v-model="form.title"
							placeholder='请填写联系微信' input-align="right" /></u-form-item>
					<u-form-item label="联系电话" right-icon='arrow-right'>
						<u-input v-model="form.title" placeholder='请填写联系电话' input-align="right" /></u-form-item>
					</u-form-item>
					<u-form-item label="链接" right-icon='arrow-right'><u-input v-model="form.title" placeholder='请填写链接'
							input-align="right" /></u-form-item>
				</view> -->
				<!-- <view class="form-item">
					<view class="form-title">
						详细描述
					</view>
					<u-form-item label="描述信息" right-icon='arrow-right'><u-input input-align="right"
							placeholder='点击编辑详细描述' @click='showpopup = true' readonly /></u-form-item>
				</view> -->
				<view class="form-item">
					<view class="form-title">
						置顶付费设置
					</view>
					<u-form-item label="是否置顶付费" right-icon='arrow-right'>
						<view class="flex-end">
							<u-switch v-model="isTopPay" size='28'></u-switch>
						</view>

					</u-form-item>
					<u-form-item label="置顶套餐" right-icon='arrow-right' v-if="isTopPay">
						<view class="flex-end">
							<u-radio-group wrap v-model="topConfigVal">
								<u-radio v-for="(item, index) in topList" :key="index" :name="item.value"
									:disabled="item.disabled">
									{{item.label}}
								</u-radio>
							</u-radio-group>
						</view>
					</u-form-item>

				</view>
				<view style="width: 100%; height: 20rpx;"></view>
			</u-form>
			<view class="submit-btn">
				<u-button type="primary" shape="circle" @click="submit">发布</u-button>
			</view>
			<view style="width: 100%; height: 20rpx;"></view>
		</view>
		<u-select v-model="areaShow" mode="single-column" :list="areaList" @confirm="areaConfirm"></u-select>
		<u-select v-model="tagsShow" mode="single-column" :list="tagsList" @confirm="tagsConfirm"></u-select>
		<u-popup v-model="showpopup" mode='bottom' height="100%">
			<view>
				<jinEdit placeholder="请输入内容" :html='form.description' @editOk="editOk" uploadFileUrl="/#"></jinEdit>
			</view>
		</u-popup>
		<!-- <Tabbar :tabbarCurrent="tabbarCurrent"></Tabbar> -->
	</view>
</template>

<script>
	var sourceType = [
		['camera'],
		['album'],
		['camera', 'album']
	]
	import jinEdit from '@/component/jin-edit/components/jin-edit/jin-edit.vue';
	import {
		releaseRoom,
		PayTopRelease,
		GetHouseDetail,
		GetHouseSkuInfo,
		UpDateRoom
	} from "@/api/index.js"
	import {
		lastIndexOf
	} from 'lodash';
	export default {
		components: {
			jinEdit
		},
		data() {
			return {
				tabbarCurrent: 1,
				showpopup: false,
				topShow: false,
				action: 'https://aiyouzixun.top/prod-api/api/v1/alioss/upload',
				// fileList: [],
				skuList: [{
						title: "短期1个月押1付1",
						price: "",
						commission: "",
						leaseMonth: 1,
						isShow: false
					},
					{
						title: "签3个月押1付1",
						price: "",
						commission: "",
						leaseMonth: 1,
						isShow: false
					},
					{
						title: "签6个月押1付1",
						price: "",
						commission: "",
						leaseMonth: 1,
						isShow: false
					},
					{
						title: "签1年押1付1",
						price: "",
						commission: "",
						leaseMonth: 1,
						isShow: false
					},
					{
						title: "签1年押1付3",
						price: "",
						commission: "",
						leaseMonth: 3,
						isShow: false
					},
					{
						title: "签1年押1付6",
						price: "",
						commission: "",
						leaseMonth: 6,
						isShow: false
					},
					{
						title: "签1年押1付12",
						price: "",
						commission: "",
						leaseMonth: 12,
						isShow: false
					},
				],
				checked: false,
				priceTypeCurrent: 0,
				priceType: [{
						name: '免中介费'
					},
					{
						name: '收中介费'
					},
				],
				areaList: [{
						value: '南明区',
						label: '南明区'
					},
					{
						value: '云岩区',
						label: '云岩区'
					},
					{
						value: '观山湖区',
						label: '观山湖区'
					},
					{
						value: '白云区',
						label: '白云区'
					},
					{
						value: '乌当区',
						label: '乌当区'
					},
					{
						value: '花溪区',
						label: '花溪区'
					},
				],
				tagsList: [{
						value: '合租单间',
						label: '合租单间'
					},
					{
						value: '单间带卫浴',
						label: '单间带卫浴'
					},
					{
						value: '一室一厅',
						label: '一室一厅'
					},
					{
						value: '二室一厅',
						label: '二室一厅'
					},
					{
						value: '三室一厅',
						label: '三室一厅'
					},
					{
						value: '四室以上',
						label: '四室以上'
					},
					{
						value: '公寓',
						label: '公寓'
					},
				],
				areaShow: false,
				tagsShow: false,
				form: {
					title: "",
					isshowAddr: 0,
					skuList: [],
					description: "",
					position: "",
					address: "",
					images: "",
					openId: "123",
					area: "",
					postUrl: "",
					topStartTime: 0,
					topEndTime: 0,
					tags: "",
					isAgency: 0,
					housePassword: ''
				},
				isShowAddlist: [{
						name: '是',
						disabled: false
					},
					{
						name: '否',
						disabled: false
					},
				],
				topList: [],
				topConfigVal: "",
				isTopPay: false,
				houseId: '',
				isUploadSuccess: false,

				imageList: [], //图片
				src: "", //视频存放
				sourceTypeIndex: 2,
				checkedValue: true,
				checkedIndex: 0,
				sourceType: ['拍摄', '相册', '拍摄或相册'],
				cameraList: [{
						value: 'back',
						name: '后置摄像头',
						checked: 'true'
					},
					{
						value: 'front',
						name: '前置摄像头'
					},
				],
				cameraIndex: 0,
				VideoOfImagesShow: true,
			}
		},
		computed: {
			platformMoney() {
				let userInfo = uni.getStorageSync('userInfo')
				let appCOnfig = uni.getStorageSync('APP_CONFIG')
				if (this.form.isAgency == 1) {
					return userInfo.platformAgencyMoney || appCOnfig.platformAgencyMoney
				} else {
					return userInfo.platformNotAgencyMoney || appCOnfig.platformNotAgencyMoney
				}
			}
		},
		onUnload() {
			this.src = '',
				this.sourceTypeIndex = 2,
				this.sourceType = ['拍摄', '相册', '拍摄或相册'];
		},
		onLoad(op) {
			this.getconfigList()
			if (op.id) {
				this.houseId = op.id
				this.getHouseDetail()
			}
		},
		methods: {
			// chooseVideoImage() {
			// 	let that = this
			// 	uni.showActionSheet({
			// 		title: "选择上传类型",
			// 		itemList: ['图片', '视频'],
			// 		success: (res) => {
			// 			if (res.tapIndex == 0) {
			// 				that.chooseImages()
			// 			} else {
			// 				that.chooseVideo()
			// 			}
			// 		}
			// 	})
			// },
			chooseImages() {
				let that = this

				// 上传图片
				uni.chooseImage({
					count: 9, //默认9
					// sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						const len = res.tempFilePaths.length;
						const totalLen = that.imageList.length + len
						if (totalLen > 9) {
							uni.showToast({
								title: '图片最多上传9张！',
								icon: 'none'
							})
							return
						}
						uni.showLoading({
							title: '上传中...'
						});
						let igmFile = res.tempFilePaths.map(blobUrl => ({
							name: 'file',
							file: blobUrl,
							uri: blobUrl
						}));
						uni.uploadFile({
							url: that.action,
							method: "POST",
							header: {
								'Authorization': uni.getStorageSync('Authorization'),
								// 'Content-Type': 'multipart/form-data' //如果行就把这个删掉
							},
							files: igmFile,
							// filePath: igmFile[0],
							// name: 'file',
							success: (res) => {
								let imgUrls = JSON.parse(res.data); //微信和头条支持
								// let imgUrls = res.data //百度支持
								// that.imagesUrlPath = that.imagesUrlPath.concat(imgUrls.result
								// 	.filePath);
								that.imageList = that.imageList.concat(imgUrls.data)
								// //微信
								// if (that.imageList.length >= 9) {
								// 	that.VideoOfImagesShow = false;
								// } else {
								// 	that.VideoOfImagesShow = true;
								// }
								wx.hideLoading();
							}
						})
						// this.imageList = this.imageList.concat(res.tempFilePaths)  //头条
					},
				});
			},
			chooseVideo() {
				let that = this
				if (that.src != '') {
					uni.showToast({
						title: "你已经上传视频了！",
						icon: 'none'
					})
					return
				}
				// 上传视频
				uni.chooseVideo({
					maxDuration: 60,
					count: 1,
					camera: that.cameraList[that.cameraIndex].value,
					sourceType: ['album'],
					success: (responent) => {
						uni.showLoading({
							title: '上传中...'
						});
						let videoFile = responent.tempFilePath;
						uni.uploadFile({
							url: that.action,
							method: "POST",
							header: {
								'Authorization': uni.getStorageSync('Authorization')
							},
							filePath: videoFile,
							name: 'file',
							success: (res) => {
								let videoUrls = JSON.parse(res.data) //微信和头条支持
								// let videoUrls = res.data //百度支持
								// that.imagesUrlPath = that.imagesUrlPath.concat(videoUrls.result
								// 	.filePath);
								that.src = videoUrls.data[0].url; //微信
								if (that.src) {
									that.itemList = ['图片']
								} else {
									that.itemList = ['图片', '视频']
								}
								wx.hideLoading();
							}
						})
						// that.src = responent.tempFilePath;  //头条
					}
				})
			},
			previewImage(e) {
				//预览图片
				// var current = e.target.dataset.src
				let imgList = this.imageList.map(ele => {
					return ele.url
				})
				uni.previewImage({
					current: e,
					urls: imgList
				})
			},
			delect(index) {
				uni.showModal({
					title: "提示",
					content: "是否要删除该图片",
					success: (res) => {
						if (res.confirm) {
							this.imageList.splice(index, 1)
						}
					}
				})
			},
			delectVideo() {
				uni.showModal({
					title: "提示",
					content: "是否要删除此视频",
					success: (res) => {
						if (res.confirm) {
							this.src = ''
						}
					}
				})
			},
			getHouseDetail() {
				GetHouseDetail({
					id: this.houseId
				}).then(res => {
					this.form = res.data
					this.form.images = this.form.images.split(',')

					this.form.images.forEach(ele => {
						const extIndex = ele.lastIndexOf('.');
						const extName = ele.slice(extIndex + 1)
						if (extName == 'mp4' || extName == 'mov') {
							this.src = ele
						} else {
							this.imageList.push({
								url: ele
							})
						}
					})
					this.getSkuInfo()
				})
			},
			getSkuInfo() {
				let that = this
				let query = {
					houseId: this.houseId
				}
				GetHouseSkuInfo(query).then(res => {
					const skuMap = res.data.reduce((prev, cur) => {
						prev[cur.title] = cur;
						return prev;
					}, {})
					that.skuList.forEach(item => {
						if (skuMap[item.title]) {
							item.isShow = true
							item = Object.assign(item, skuMap[item.title])
						}
					})
				})
			},
			// 支付
			pay(params) {
				WeixinJSBridge.invoke('getBrandWCPayRequest', params, res => {
					if (res.err_msg == "get_brand_wcpay_request:ok") {
						//支付成功
						// resolve(true)
						if (this.houseId) {
							uni.showToast({
								title: "修改成功！",
								duration: 800
							})
						} else {
							uni.showToast({
								title: "发布成功！",
								duration: 800
							})
						}

						setTimeout(() => {
							uni.switchTab({
								url: '/pages/mine/index'
							})
						}, 1000)
					} else {
						//支付失败
						// resolve(false)
						uni.showToast({
							title: "置顶付费失败！",
							duration: 800
						})
					}
				})
			},
			// 获取置顶配置信息
			getconfigList() {
				let config = uni.getStorageSync('APP_CONFIG')

				let obj = {
					value: "topChargeMonth",
					label: `包月置顶:${config.topChargeMonth}`,
					disabled: false
				}
				let obj1 = {
					value: 'topChargeYear',
					label: `包年置顶:${config.topChargeYear}`,
					disabled: false
				}
				this.topList.push(obj)
				this.topList.push(obj1)
			},
			subChange(index) {
				this.form.isAgency = index
			},
			editOk(res) {
				this.form.description = res.html
				this.showpopup = false
			},
			selectAddress() {
				let that = this
				uni.chooseLocation({
					success: function(res) {
						that.form.address = res.address
						that.form.position = res.longitude + ',' + res.latitude
					}
				});
			},
			areaConfirm(e) {
				this.form.area = e[0].value
			},
			tagsConfirm(e) {
				this.form.tags = e[0].value
			},
			showArea() {
				this.areaShow = true
			},
			showTags() {
				this.tagsShow = true
			},
			// 选中某个单选框时，由radio时触发
			radioChange(e) {},
			// 选中任一radio时，由radio-group触发
			radioGroupChange(e) {
				if (e == '是') {
					this.form.isshowAddr = 1
				}
				if (e == '否') {
					this.form.isshowAddr = 0
				}
			},
			onSuccess(data) {
				let that = this
				let files = [];
				files = that.$refs.uUpload.lists.filter(val => {
					return val.progress == 100;
				})
				if (files.length != 0) {
					let images = []
					files.forEach(ele => {
						images.push(ele.response.data[0].url)
					})
					that.form.images = images.join()
				}
				// this.isUploadSuccess = true
			},
			submit() {
				let that = this
				if (that.form.title == '') {
					uni.showToast({
						title: '请填写房源标题！',
						icon: 'none'
					})
					return
				}
				if (that.form.area == '') {
					uni.showToast({
						title: '请选择房源区域！',
						icon: 'none'
					})
					return
				}
				// if (that.form.address == '') {
				// 	uni.showToast({
				// 		title: '请选择房源地址！',
				// 		icon: 'none'
				// 	})
				// 	return
				// }
				if (that.form.tags == '') {
					uni.showToast({
						title: '请选择房源户型！',
						icon: 'none'
					})
					return
				}



				if (that.isTopPay && that.topConfigVal == '') {
					uni.showToast({
						title: '请选择置顶套餐！',
						icon: 'none'
					})
					return
				}

				let trueSkuList = that.skuList.filter(ele => {
					return ele.isShow
				})
				that.form.skuList = trueSkuList
				if (that.form.skuList.length == 0) {
					uni.showToast({
						title: '请填写房源收费信息！',
						icon: 'none'
					})
					return
				}
				for (var i = 0; i < that.form.skuList.length; i++) {
					if (that.form.skuList[i].price == '') {
						uni.showToast({
							title: `请填写${that.form.skuList[i].title}的价格`,
							icon: 'none'
						})
						return;
					}
					if (that.form.skuList[i].commission == '') {
						uni.showToast({
							title: `请填写${that.form.skuList[i].title}的佣金`,
							icon: 'none'
						})
						return;
					}
				}
				that.form.openId = uni.getStorageSync('userInfo').openId
				let images = []
				if (that.imageList.length != 0) {
					that.imageList.forEach(ele => {
						images.push(ele.url)
					})
				}
				if (that.src != '') {
					images.push(that.src)
				}
				that.form.images = images.join()
				if (that.houseId) {
					// 编辑
					UpDateRoom(that.form).then(res => {
						if (that.isTopPay) {
							//唤起
							let query = {
								openId: that.form.openId,
								houseId: res.data.id,
								payPackage: that.topConfigVal
							}
							return PayTopRelease(query)
						}
						uni.showToast({
							title: "修改成功！",
							duration: 800
						})
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/mine/index'
							})
						}, 1000)
					}).then(res => {
						if (res) {
							that.pay(res);
						}
					})
				} else {
					// 新增
					releaseRoom(that.form).then(res => {
						if (that.isTopPay) {
							//唤起
							let query = {
								openId: that.form.openId,
								houseId: res.data.id,
								payPackage: that.topConfigVal
							}
							return PayTopRelease(query)
						}
						uni.showToast({
							title: "发布成功！",
							duration: 800
						})
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/mine/index'
							})
						}, 1000)
					}).then(res => {
						if (res) {
							that.pay(res);
						}
					})
				}
			},
		}
	}
</script>

<style lang="scss">
	.tips-box {
		background-color: #B4FDFF;
		color: #0014B7;
		padding: 10rpx;
		font-size: 26rpx;
	}

	.form-item {
		width: 95%;
		margin: 0 auto;
		margin-top: 20rpx;
		background-color: #fff;
		padding: 20rpx;
		border-radius: 10rpx;

		.form-title {
			font-size: 32rpx;
			font-weight: bold;
		}
	}

	.flex-end {
		width: 100%;
		display: flex;
		justify-content: flex-end;
	}

	.price-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		white-space: nowrap;

		.input-item {
			display: flex;
			align-items: center;
			width: 28%;
		}
	}

	.uni-input-placeholder {
		font-size: 24rpx;
	}

	/deep/ .uni-input-input {
		font-size: 24rpx;
	}

	.submit-btn {
		width: 95%;
		margin: 0 auto;
	}

	.burst-wrap {
		width: 100%;
		height: 100%;
	}

	/* .burst-wrap .burst-wrap-bg{
	    position: relative;
	    width: 100%;
	    height: 320upx;
	    background:linear-gradient(90deg,rgba(251,91,80,1) 0%,rgba(240,45,51,1) 100%);
	    border-bottom-right-radius: 80upx;
	    border-bottom-left-radius: 80upx;
	} */
	.burst-wrap .burst-wrap-bg>view {
		width: 90%;
		height: 100%;
		margin: 0 auto;
		position: absolute;
		top: 65upx;
		left: 0;
		right: 0;
	}

	.form-item {
		width: 100%;
	}

	.form-item textarea {
		display: block;
		height: 220upx;
		width: 100%;
		color: #AAAAAA;
		font-size: 28upx;
	}

	.uni-uploader__file,
	.uploader_video {
		position: relative;
		z-index: 1;
		width: 150upx;
		height: 150upx;
		margin-right: 10rpx;
		margin-top: 10rpx;
	}

	.uni-uploader__img {
		width: 200upx;
		height: 200upx;
	}

	.icon-cuo {
		position: absolute;
		right: 10upx;
		font-size: 26rpx;
		top: 5upx;
		color: #FFFFFF;
		padding: 10rpx;
		border-radius: 50%;
		background-color: rgba(0, 0, 0, 0.6);
		// font-weight: bold;
		z-index: 999;
	}

	.video {
		width: 100%;
		height: 100%;
	}

	.login-input-box {
		position: relative;
		border-bottom: 1upx solid #EEEEEE;
	}

	.login-input-box .forget,
	.login-input-box .phone {
		position: absolute;
		top: 0;
		height: 100%;
		z-index: 100;
	}

	.login-input-box .phone {
		width: 100upx;
		left: 0;
		color: #666666;
		font-weight: bold;
	}

	.login-input-box .phone-input {
		padding-left: 100upx;
	}

	.address-wrap,
	.open-info {
		margin-top: 20upx;
	}

	.open-info>view:last-child {
		font-size: 28upx;
		color: #999999;
	}

	.address-wrap .address {
		background: #F2F2F2;
		border-radius: 40upx;
		padding: 0 20upx;
	}

	.user-set-btn {
		margin: 40upx;
		background: linear-gradient(90deg, rgba(251, 91, 80, 1) 0%, rgba(240, 45, 51, 1) 100%);
		color: #FFFFFF;
		text-align: center;
		height: 88upx;
		line-height: 88upx;
	}

	.upload-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 20rpx;
		background: #eee;
		border-radius: 5px;
		margin: 10rpx;

		>image {
			width: 50rpx;
		}
	}
</style>